import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../components/Login.vue'
import jwtDecode from 'jwt-decode'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'login',
    component: login,
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../components/register.vue'),
  },
  {
    path: '/Home',
    name: 'Home',
    component: () => import('../components/Home.vue'),
    children:[
      {
        path: '/HomeIndex',
        name: 'HomeIndex',
        component: () => import('../components/HomeIndex.vue'),
      },
      {
        path: '/HomeHome',
        name: 'HomeHome',
        component: () => import('../components/HomeHome.vue'),
      },
      {
        path: '/personal',
        name: 'personal',
        component: () => import('../components/personal.vue'),
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 路由守卫
router.beforeEach((to,from,next)=>{
  if(to.path==='/' || to.path ==='/register'){
    next()     
  }else{
    let token = localStorage.getItem('token')
    if(!token){
      next('/')
    }else{
      let {exp,iat} = jwtDecode(token)
      let newDate = new Date().getTime()
      newDate = Math.floor(newDate/1000)
      if(exp - newDate>=0){
        next()
      }else{
        next('/login')
      }
    }
  }
})
export default router
